import axios from 'axios'

function request(url, data, loading = true, timeout, method, content, cancel, download = false) {
  loading && this.loading.show()
  let config = {
    url,
    method,
    baseURL: url.startsWith('http') ? '' : (process.env.VUE_APP_BASE_URL || ''),
    [method === 'post' ? 'data' : 'params']: data || {},
    timeout: timeout || 5000,
    headers: { 'X-Requested-With': 'XMLHttpRequest' }
  }
  content && (config.headers['Content-Type'] = content)
  cancel && (config.cancelToken = cancel.token)
  download && (config.responseType = 'blob')
  return axios(config).then(response => {
    const data = response.data
    if (data.status === 10) {
      if (!this.$root.referrer) {
        this.$router.replace({
          path: '/login'
        })
      } else {
        window.location.replace(`${this.$root.referrer}#/login`)
      }
    } else if (data.status === 2) {
      this.toastr.error(`${url}接口参数错误`)
    }
    if (download) {
      downloadFile.call(this, response, loading)
      return true
    }
    return data
  }).catch(error => {
    download && this.loading.close()
    this.toastr.error(error.message)
  }).finally(() => {
    (loading && !download) && this.loading.close()
  })
}

function get(url, data, config) {
  config = config || {}
  return request.call(this, url, data, config.loading, config.timeout, 'get', null, config.cancel, config.download)
}

function post(url, data, config) {
  config = config || {}
  let content = 'application/json;charset=UTF-8'
  if (Object.prototype.toString.call(data) === '[object FormData]') {
    content = 'multipart/form-data'
  }
  return request.call(this, url, data, config.loading, config.timeout, 'post', content, config.cancel, config.download)
}

function downloadFile(response, loading) {
  const blob = new Blob([response.data]),
    filename = response.headers['content-disposition'].split('=')[1].replace(/"/g, '')
  if (window.navigator.msSaveOrOpenBlob) {
    // 兼容IE10
    navigator.msSaveBlob(blob, filename)
  } else {
    // chrome/firefox
    let aTag = document.createElement('a')
    aTag.download = filename
    aTag.href = URL.createObjectURL(blob)
    aTag.click()
    URL.revokeObjectURL(aTag.href)
  }
  loading && this.loading.close()
}

/*
  url：接口地址，不带http会去.env里面配置的VUE_APP_BASE_URL上的值
  data：请求参数
  config：配置项
    loading：是否需要请求提示
    timeout：请求超时时间
    cancel：取消请求的对象
      const source = axios.CancelToken.source()
      config.cancel = source
      使用：source.cancel('xxxxxx')
*/
export default function(Vue) {
  Vue.prototype.axios = axios
  Vue.prototype.$get = get
  Vue.prototype.$post = post
}